package com.eagle.epay.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eagle.epay.entity.Monitor;
import com.eagle.epay.entity.PayInfo;
import com.eagle.epay.service.IMonitorService;
import org.jdom.CDATA;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.EscapeStrategy;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author eagle
 * @since 2020-01-03
 */
@RestController
@RequestMapping("/monitor")
public class MonitorController {
	@Autowired
	private IMonitorService monitorService;

//	http://localhost:8080/monitor/genxml
	@GetMapping("genxml")
	@ResponseBody
	public String getXML() throws Exception{
		QueryWrapper<Monitor> wrapper = new QueryWrapper<>();
		List<Monitor> list = monitorService.list(wrapper);
		String result = createXml(list);
		return result;
	}

  private String createXml(List<Monitor> list){
	try {
		Element root = new Element("root");
		Document document = new Document(root);

		Element dataBases = new Element("DataBases");
		dataBases.setAttribute("Interval","1");
		root.addContent(dataBases);

		for (Monitor monitor : list) {
			Element dataBase = new Element("DataBase");
			dataBase.setAttribute("MonitorType","0");
			dataBase.setAttribute("baseValue","1");
			CDATA sqlData = new CDATA(monitor.getSqlcmd());
			dataBase.setAttribute("sql",monitor.getSqlcmd());
			dataBase.setAttribute("Name",monitor.getName());
			dataBase.setAttribute("ConnectString","");
			dataBase.setAttribute("BusinessSystem","7");
			dataBases.addContent(dataBase);

			Element msg = new Element("Msg");
			CDATA titleData = new CDATA(monitor.getTittle());
			msg.addContent(titleData);
			dataBase.addContent(msg);

			Element processingMethod = new Element("ProcessingMethod");
			CDATA contentData = new CDATA(monitor.getContent());
			processingMethod.addContent(contentData);
			dataBase.addContent(processingMethod);
		}

		Format format = Format.getCompactFormat();
		// 设置换行Tab或空格
		format.setIndent("	");
		format.setEncoding("UTF-8");

		// 4、创建XMLOutputter的对象
		XMLOutputter outputer = new XMLOutputter(format);
		// 5、利用outputer将document转换成xml文档
		File file = new File("MonitorConfig.xml");
		outputer.output(document, new FileOutputStream(file));



		return "生成MonitorConfig.xml成功";
	} catch (Exception e) {
		e.printStackTrace();
	}
	  return "生成MonitorConfig.xml失败";
}

}

